<template>
  <div class="warn-container">
    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :model="searchForm" inline>
        <el-form-item label="货品名称">
          <el-input
            v-model="searchForm.productName"
            placeholder="请输入货品名称"
            clearable
          />
        </el-form-item>
       
        <el-form-item label="上限">
            <el-input
            v-model="searchForm.upper"
            placeholder="请输入上限"
            clearable
          />
        </el-form-item>
        <el-form-item label="下限">
          <el-input
            v-model="searchForm.lower"
            placeholder="请输入下限"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      
      <el-button @click="handleRefresh">刷新</el-button>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-table 
        :data="tableData" 
        style="width: 100%;" 
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="productCode" label="货品编号" width="120" />
        <el-table-column prop="productName" label="货品名称" min-width="150" />
        <el-table-column prop="specifications" label="规格型号" width="120" />
        <el-table-column prop="categoryName" label="货品类型" width="100" />
        <el-table-column prop="currentStock" label="当前库存" width="100">
          <template #default="scope">
            <span class="stock-number" :class="getStockClass(scope.row)">
              {{ scope.row.currentStock }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="lower" label="库存下限" width="100">
          <template #default="scope">
            <span class="limit-number lower">{{ scope.row.lower }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="upper" label="库存上限" width="100">
          <template #default="scope">
            <span class="limit-number upper">{{ scope.row.upper }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="belowLowerPercent" label="低于下限" width="120">
          <template #default="scope">
            <el-tag 
              v-if="scope.row.belowLowerPercent > 0"
              type="danger" 
              size="small"
            >
              {{ scope.row.belowLowerPercent }}%
            </el-tag>
            <span v-else class="normal-text">正常</span>
          </template>
        </el-table-column>
        <el-table-column prop="aboveUpperPercent" label="高于上限" width="120">
          <template #default="scope">
            <el-tag 
              v-if="scope.row.aboveUpperPercent > 0"
              type="warning" 
              size="small"
            >
              {{ scope.row.aboveUpperPercent }}%
            </el-tag>
            <span v-else class="normal-text">正常</span>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.PageIndex"
        v-model:page-size="pagination.PageSize"
        :total="pagination.totalCount"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import PurSale from '@/http/PurSale'
import { ElMessage } from 'element-plus'
import http from '@/http/axiosHelper'
// 搜索表单数据
const searchForm = reactive({
  productName: '',
  upper:'',
  lower:''
})

// 分页数据
const pagination = reactive({
  PageIndex: 1,
  PageSize: 10,
  totalCount: 0,
  totalPage: 0
})

// 表格数据
const tableData = ref<any[]>([])
const loading = ref(false)
const selectedRows = ref<any[]>([])

// 获取库存状态样式类
const getStockClass = (row: any) => {
  if (row.currentStock < row.lowerLimit) {
    return 'stock-low'
  } else if (row.currentStock > row.upperLimit) {
    return 'stock-high'
  }
  return 'stock-normal'
}

// 搜索方法
const handleSearch = async () => {
  loading.value = true
  try {
    const params = {
      PageIndex: pagination.PageIndex,
      PageSize: pagination.PageSize,
      ProductName: searchForm.productName,
      Lower: searchForm.lower || undefined,
      Upper: searchForm.upper || undefined
    }
    
    try {
      const response = await http.get('/scmreadconsul/api/Ledger/ShowWarn', { params })
      
      if (response.data.code === 200) {
        tableData.value = response.data.items || []
        pagination.totalCount = response.data.totalCount || 0
        pagination.totalPage = response.data.totalPage || 0
        ElMessage.success('查询成功')
      } else {
        ElMessage.error(response.data.msg || '查询失败')
      }
    } catch (apiError) {
      console.error('API调用失败:', apiError)
      // 如果API调用失败，使用模拟数据
      const mockData = generateMockData()
      tableData.value = mockData
      pagination.totalCount = 100
      pagination.totalPage = 10
      ElMessage.warning('使用模拟数据，API接口暂时不可用')
    }
  } catch (error) {
    console.error('查询失败:', error)
    ElMessage.error('查询失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 生成模拟数据
const generateMockData = () => {
  const mockData = []
  const productCodes = ['HPDH4049', 'HPDH6064', 'HPDH5235', 'HPDH40', 'HPDH6334', 
                       'HPDH5236', 'HPDH7065', 'HPDH6559', 'HPDH3726', 'HPDH226']
  const productNames = ['货品一', '货品二', '货品三', '货品四', '货品五', 
                       '货品六', '货品七', '货品八', '货品九', '货品十']
  const specifications = ['600ml', '红', '90*20', '蓝', '1kg', '500ml', '绿', '80*15', '黄', '2kg']
  
  for (let i = 0; i < 10; i++) {
    const currentStock = 50
    const lowerLimit = 10
    const upperLimit = 100
    
    // 计算百分比
    const belowLowerPercent = currentStock < lowerLimit ? 
      Math.round(((lowerLimit - currentStock) / lowerLimit) * 100) : 0
    const aboveUpperPercent = currentStock > upperLimit ? 
      Math.round(((currentStock - upperLimit) / upperLimit) * 100) : 0
    
    mockData.push({
      serialNumber: i + 1,
      productCode: productCodes[i],
      productName: productNames[i],
      specifications: specifications[i],
      unitName: '件',
      categoryName: '饮品',
      currentStock: currentStock,
      lowerLimit: lowerLimit,
      upperLimit: upperLimit,
      belowLowerPercent: belowLowerPercent,
      aboveUpperPercent: aboveUpperPercent
    })
  }
  
  return mockData
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    (searchForm as any)[key] = ''
  })
  pagination.PageIndex = 1
  handleSearch()
}

// 导出数据
const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

// 刷新数据
const handleRefresh = () => {
  handleSearch()
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.PageSize = size
  pagination.PageIndex = 1
  handleSearch()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.PageIndex = page
  handleSearch()
}

// 选择行变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 组件挂载时加载数据
onMounted(() => {
  handleSearch()
})
</script>

<style scoped>
.warn-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.search-form {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.action-buttons {
  background-color: white;
  padding: 15px 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-container {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-container {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  display: flex;
  justify-content: flex-end;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.el-form-item {
  margin-bottom: 15px;
}

.el-button {
  margin-right: 10px;
}

.el-table {
  margin-top: 10px;
}

.stock-number {
  font-weight: bold;
  font-size: 14px;
}

.stock-number.stock-low {
  color: #f56c6c;
}

.stock-number.stock-high {
  color: #e6a23c;
}

.stock-number.stock-normal {
  color: #67c23a;
}

.limit-number {
  font-weight: bold;
  font-size: 14px;
}

.limit-number.lower {
  color: #f56c6c;
}

.limit-number.upper {
  color: #e6a23c;
}

.normal-text {
  color: #67c23a;
  font-size: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .warn-container {
    padding: 10px;
  }
  
  .search-form .el-form-item {
    margin-bottom: 10px;
  }
}
</style>
